package com.jason.auto.common;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public GeneralResult onException(Exception e) {
        //增加打印日志
        log.error(e.getMessage(), e);
        return new GeneralResult(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(BizException.class)
    public GeneralResult handleBizException(BizException e) {
        return new GeneralResult(e.getErrorCode(), e.getMessage());
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public GeneralResult onNoHandlerFoundException(NoHandlerFoundException e) {
        return new GeneralResult(ResultCode.RESOURCE_NOT_FOUND.getCode(), e.getMessage());
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public GeneralResult onMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        JSONObject error = new JSONObject();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            error.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new GeneralResult(ResultCode.PARAM_ERROR.getCode(), error.toJSONString());
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public GeneralResult onHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return new GeneralResult(ResultCode.PARAM_ERROR.getCode(), e.getMessage());
    }
}
